var fs = require('fs')
var paths = require('../config/pathConfig.js')
var util = require('../utility/util.js')
var Promise = require('bluebird')

module.exports = {
  getTestList: function (filter, callback) {
    var testTopicPath = paths.testTopicPath

    fs.readdir(testTopicPath, function(err, files) {
      if (err) {
        console.log('读取data文件失败')
      } else {
        files = files.filter(function(item) {
          return item.indexOf('DS_Store') == -1
        })

        if (filter) {
          if (filter.leavel) {
            var patt = new RegExp('^' + filter.leavel + '\-')
            files = files.filter(function (file) {
              return patt.test(file)
            })
          } else if(filter.user) {
            var patt = new RegExp('\-' + user + '.data$')
            files = files.filter(function (file) {
              return patt.test(file)
            })
          }
        }

        var promiseAll = []
        files.map(function(file) {
          promiseAll.push(new Promise(function(resolve, reject) {
            fs.readFile(path.join(testTopicPath, file), function(err, data) {
              if (err) {
                reject('读取文件失败')
              } else {
                resolve(JSON.parse(data))
              }
            })
          }))
        })
        Promise.all(promiseAll).then(function(resArr) {
          //  按创建时间倒序
          resArr.sort(function (obj1, obj2) {
            return new Date(obj2.createdAt) - new Date(obj1.createdAt)
          })
          callback(null, resArr)
        }).catch(function(err) {
          console.log('读取文件失败，err = ' + err.message)
          callback(err)
        })
      }
    })
  }
}